package br.com.lm.geral.util;

import java.io.Serializable;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;

/**
 * @author Robson Motta
 */
public class MessageProvider implements Serializable {

    private String resourceBundleVar;
    private ResourceBundle bundle;
    
    /**
     * @param resourceBundleVar: nome do Resource Bundle em faces-config.xml
     * Ex: <resource-bundle>...<var>resourceBundleVar</var></resource-bundle>
     */
    public MessageProvider(String resourceBundleVar) {
        this.resourceBundleVar = resourceBundleVar;
    }
    
    @SuppressWarnings("LocalVariableHidesMemberVariable")
    public ResourceBundle getBundle() {
       FacesContext ctx = FacesContext.getCurrentInstance();
       String localeBundle   = bundle == null ? "" : bundle.getLocale().toString();
       String localeViewRoot = ctx.getViewRoot().getLocale().toString();
       if (!localeBundle.equals(localeViewRoot))
           bundle = null;
        if (bundle == null) {            
            try {bundle = ctx.getApplication().getResourceBundle(ctx, resourceBundleVar);}
            catch(Exception e){}
        }
        return bundle;
    }
     
    @SuppressWarnings("UnusedAssignment") 
    public String getValueFromKey(String key) {
        String result = null;
        try {
            ResourceBundle myBundle = getBundle();
            if (myBundle != null)
                result = myBundle.getString(key);
        } catch (MissingResourceException e) {
            result = "???" + key + "??? não encontrado no arquivo de mensagens";
        }
        return result;
    }
        
    public String getResourceBundleVar() {
        return resourceBundleVar;
    }
}